package wec_wallet.ebo.com.common;


import android.content.Context;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import wec_wallet.ebo.com.utils.URLs;
import bassproject.ebo.com.ebobass.utils.I_Share;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import wec_wallet.ebo.com.util.StringUtil;

/**
 * 项目名：okhttp的封装
 * 创建人：王莹
 * 创建时间：2016/11/21
 * 修改日期：
 * 备注：
 */
public class HttpUtils {
    public static final MediaType JSON
            = MediaType.parse("application/json; charset=utf-8");
    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
    public static OkHttpClient client = new OkHttpClient();
    private final OkHttpClient client2 = new OkHttpClient();

    //okhttp异步方法
    public static Call post(String method, RequestBody json, Callback callbacks) throws IOException {
        //把请求的内容字符串转换为json
//        RequestBody body = RequestBody.create(JSON, json);
        String url =  method;    //这里写的是地址
        Request request = new Request.Builder()
                .url(url)
                .post(json)
                .build();

        Call call = client.newCall(request);
        call.enqueue(callbacks);

        return call;

    }

    /**
     * 上传文件
     *
     * @param method    方法名（url后接方法名）
     * @param parm      文件参数名
     * @param path      文件路径
     * @param maps      上传参数
     * @param callbacks 返回
     * @return
     * @throws IOException
     */
    public static Call uploadFile(String method, String parm, String path, Map<String, String> maps, Callback callbacks) throws IOException {
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        for (String key : maps.keySet()) {
            builder.addFormDataPart(key, maps.get(key));
        }
        if (!StringUtil.isStringEmpty(path)) {
            File file = new File(path);
            String fileNameAndType = StringUtil.getFileNameAndType(path);//获取文件和后缀名
            builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + parm + "\";filename=\"" + fileNameAndType + "\""),
                    RequestBody.create(MediaType.parse("image/png"), file)
            );
        }

        RequestBody body = builder.build();
        String url = URLs.BASE_URL+ I_Share.getLanguageType_String()+method;
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        Call call = client.newCall(request);
        call.enqueue(callbacks);
        return call;
    }


    public static Response uploadFileSync(String method, String parm, String path, Map<String, String> maps) throws IOException {
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        for (String key : maps.keySet()) {
            builder.addFormDataPart(key, maps.get(key));
        }
        if (!StringUtil.isStringEmpty(path)) {
            File file = new File(path);
            String fileNameAndType = StringUtil.getFileNameAndType(path);//获取文件和后缀名
            builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + parm + "\";filename=\"" + fileNameAndType + "\""),
                    RequestBody.create(MediaType.parse("image/png"), file)
            );
        }

        RequestBody body = builder.build();
        String url = URLs.BASE_URL + I_Share.getLanguageType_String() + method;
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        Call call = client.newCall(request);
        return call.execute();
    }


    /**
     * 下载文件
     *
     * @param url 下载地址
     * @return
     */
    public static Call downAsynFile(final Context context, String url, Callback callbacks) throws IOException {
        final Request request = new Request.Builder().url(url).build();
        Call call = client.newCall(request);
        call.enqueue(callbacks);

        return call;
//        client.newCall(request).enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                Log.e("wy", e.getMessage());
//                Toast.makeText(context, R.string.download_file, Toast.LENGTH_SHORT).show();
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) {
//                InputStream inputStream = response.body().byteStream();
//                FileOutputStream fileOutputStream = null;
//                try {
//                    fileOutputStream = new FileOutputStream(new File(path, fileNam));
//                    byte[] buffer = new byte[2048];
//                    int len = 0;
//                    while ((len = inputStream.read(buffer)) != -1) {
//                        fileOutputStream.write(buffer, 0, len);
//                    }
//                    fileOutputStream.flush();
//
//                } catch (IOException e) {
//                    Log.i("wangshu", "IOException");
//                    e.printStackTrace();
//                }
//
//                Log.d("wy", "文件下载成功");
//
//                Toast.makeText(context, R.string.download_success + path, Toast.LENGTH_SHORT).show();
//            }
//        });

    }

    private Call uploadMultiFiles(String method, String parm, List<String> filePaths, Map<String, String> maps, Callback callbacks) {

        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);


        if (maps != null) {
            for (String key : maps.keySet()) {
                builder.addFormDataPart(key, maps.get(key));
            }
        }

        if (filePaths != null) {
            for (String imgPath : filePaths) {
                builder.addFormDataPart(parm, imgPath, RequestBody.create(MEDIA_TYPE_PNG, new File(imgPath)));
            }
        }

        RequestBody body = builder.build();
        String url = URLs.BASE_URL + I_Share.getLanguageType_String() + method;
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        Call call = client2.newCall(request);
        call.enqueue(callbacks);
        return call;
    }


}
